import json
import requests
import time
import hmac
import base64
import hashlib
import datetime
import uuid
import frappe

# 40Seas API 枚举定义
class CheckoutStatus:
    """结账状态枚举"""
    PENDING = "pending"
    CONFIRMED = "confirmed"
    INITIATED = "initiated"
    IN_TRANSIT = "in-transit"
    SCHEDULED = "scheduled"
    PARTIALLY_PAID = "partially-paid"
    PARTIALLY_REFUNDED = "partially-refunded"
    CHARGED = "charged"
    FAILED = "failed"
    CANCELED = "canceled"
    REFUNDED = "refunded"
    REFUND_INITIATED = "refund-initiated"
    REFUND_FAILED = "refund-failed"
    DISPUTED = "disputed"
    MARKED_AS_PAID = "marked-as-paid"
    OVERDUE = "overdue"
    DEFAULTED = "defaulted"

class PaymentMethod:
    """支付方式枚举"""
    CREDIT = "credit"
    ACH = "ach"
    PHONE = "phone"
    WIRE = "wire"
    CHECK = "check"

class PaymentTerm:
    """支付期限枚举"""
    IMMEDIATE = "immediate"  # 立即支付
    NET_30 = "net30"         # 30天账期
    NET_60 = "net60"         # 60天账期
    NET_90 = "net90"         # 90天账期

class Currency:
    """货币枚举"""
    USD = "USD"
    # 注意：40Seas API 目前只支持 USD
    # 如果需要支持其他货币，需要联系 40Seas 确认

class Pay400Client:
    def __init__(self):
        self.host = "https://api.40seas.com"
        #以下是测试环境
        #self.clientId = "pCTXZxhK19airysAI5wMureHJlhnv1o5"
        #self.clientsecret = "_hxYFrKtZIlapO-Ys3UrtHh8rhZ7VMgJ3_hvN0NOBqh2TAolxnE8oy3wA-Mhl-XV"
        #以下是生产环境
        self.clientId = ""
        self.clientsecret = ""
        self.accessToken = ""
        self.expiresIn = 0
        self.session = requests.Session()

    def get_headers(self):
        headers = {
            "Content-Type": "application/json",
            "authorization": f"Bearer "+str(self.accessToken)
        }
        return headers

    def get_access_token(self):
        if self.accessToken and time.time() * 1000 < self.expiresIn:
            return self.accessToken
        # 40Seas 新版正式环境认证地址
        # 旧：https://auth.40seas.com/oauth/token
        # 新：https://api.40seas.com/v1/auth
        url = self.host + "/v1/auth"
        data = {
            "grant_type": "client_credentials",
            "client_id": self.clientId,
            "client_secret": self.clientsecret
        }
        resp = self.session.post(url, json=data).json()
        self.accessToken = resp.get('access_token', '')
        self.expiresIn = int(resp.get('expires_in', 0)) + int(time.time() * 1000)
        return self.accessToken

    def _request(self, url, method, headers=None, params=None, data=None, files=None):
        full_url = self.host + url
        if method.lower() == "get":
            r = self.session.get(full_url, headers=headers, params=params)
        elif method.lower() == "post":
            if files:
                r = self.session.post(full_url, headers=headers, files=files, data=data)
            else:
                r = self.session.post(full_url, headers=headers, json=data)
        elif method.lower() == "put":
            r = self.session.put(full_url, headers=headers, json=data)
        elif method.lower() == "patch":
            r = self.session.patch(full_url, headers=headers, json=data)
        elif method.lower() == "delete":
            r = self.session.delete(full_url, headers=headers, params=params)
        # 可扩展 put, delete
        return r.json()

    # 下面皆为 API方法，参数同 TS代码
    def get_buyers(self):
        token = self.get_access_token()
        url = "/v1/buyers"
        headers = self.get_headers()
        return self._request(url, "get", headers=headers)

    def create_buyer(self, display_name, address, email=None, legal_name=None, website=None, phone=None, 
                     dba=None, external_id=None, identification=None, contacts=None, 
                     requested_credit_amount=None, currency="USD", payment_options=None):
        """
        创建买家
        
        Args:
            display_name (str): 显示名称 (必需)
            address (dict): 地址信息 (必需) - 格式: {"country": "US"}
            email (str, optional): 邮箱
            legal_name (str, optional): 法定名称
            website (str, optional): 网站
            phone (str, optional): 电话号码
            dba (list, optional): 经营名称列表
            external_id (str, optional): 外部ID
            identification (dict, optional): 身份信息 - 格式: {"type": "ein"}
            contacts (list, optional): 联系人列表
            requested_credit_amount (float, optional): 请求信用额度
            currency (str, optional): 货币类型，默认USD
            payment_options (dict, optional): 支付选项
        
        Returns:
            dict: 创建结果
        """
        token = self.get_access_token()
        url = "/v1/buyers"
        headers = self.get_headers()
        
        # 构建必需参数
        data = {
            "displayName": display_name,
            "address": address
        }
        
        # 添加可选参数
        if email:
            data["email"] = email
        if legal_name:
            data["legalName"] = legal_name
        if website:
            data["website"] = website
        if phone:
            data["phone"] = phone
        if dba:
            data["dba"] = dba
        if external_id:
            data["externalId"] = external_id
        if identification:
            data["identification"] = identification
        if contacts:
            data["contacts"] = contacts
        if requested_credit_amount:
            data["requestedCreditAmount"] = requested_credit_amount
        if currency:
            data["currency"] = currency
        if payment_options:
            data["paymentOptions"] = payment_options
            
        return self._request(url, "post", headers=headers, data=data)

    def create_checkout(self, buyer_id, amount, currency="USD", metadata=None):
        """
        创建结账表单（简化版）
        
        Args:
            buyer_id (str): 买家ID
            amount (float): 金额
            currency (str): 货币类型，默认USD
            metadata (dict, optional): 元数据
        
        Returns:
            dict: 结账表单信息
        """
        token = self.get_access_token()
        url = "/v1/checkout"
        headers = self.get_headers()
        
        # 生成唯一的结账ID
        checkout_id = f"checkout_{uuid.uuid4().hex[:16]}"
        
        # 构建数据
        data = {
            "id": checkout_id,
            "buyer": buyer_id,
            "seller": "default_seller",  # 使用默认卖家
            "amount": amount,
            "currency": currency,
            "status": CheckoutStatus.PENDING,
            "createdAt": datetime.datetime.utcnow().isoformat() + "Z",
            "updatedAt": datetime.datetime.utcnow().isoformat() + "Z"
        }
        
        if metadata:
            data["metadata"] = metadata

        resp = self._request(url, "post", headers=headers, data=data)
        return resp

    def create_payment_intent(self, checkout_id):
        """
        创建支付意图（返回支付链接）
        
        Args:
            checkout_id (str): 结账表单ID
        
        Returns:
            dict: 支付意图信息，包含 token, url 等
        """
        token = self.get_access_token()
        url = "/v1/intents/checkout"
        headers = self.get_headers()
        
        checkout_data = {"checkout": checkout_id}
        return self._request(url, "post", headers=headers, data=checkout_data)

    def get_checkout_status(self, checkout_id):
        """
        获取结账状态（用于webhook验证）
        
        Args:
            checkout_id (str): 结账表单ID
        
        Returns:
            dict: 结账状态信息
        """
        token = self.get_access_token()
        url = f"/v1/checkout/{checkout_id}"
        headers = self.get_headers()
        return self._request(url, "get", headers=headers)


